package com.cyb.beta.controller;

import com.cyb.beta.model.MenuResc;
import com.cyb.beta.model.Role;
import com.cyb.beta.model.RoleResc;
import com.cyb.beta.service.MenuRescService;
import com.cyb.beta.service.RoleService;
import com.jfinal.ext.route.ControllerBind;

import java.util.List;

/**
 * Created by Administrator on 2015/6/18.
 */
@ControllerBind(controllerKey = "/admin/role", viewPath = "admin/user")
public class RoleController extends BaseController {

    private RoleService roleService = new RoleService();

    private MenuRescService menuRescService = new MenuRescService();

    public void index() {
        setAttr("roleList", roleService.getRoleList());
        render("roleList.html");
    }

    /**
     * 查看角色
     */
    public void view() {
        Integer id = getParaToInt(Role.ID);

        setAttr("role", null != id ? Role.dao.findById(id) : "");
        render("roleForm.html");
    }

    /**
     * 修改或保存role
     */
    public void save() {
        Role role = getModel(Role.class);

        roleService.modifyModel(role);
        redirect("/admin/role");
    }

    /**
     * 删除角色
     */
    public void delete() {
        String[] ids = getParaValues("ids");
        roleService.deleteRoles(ids);
        redirect("/admin/role");
    }

    /**
     * 角色权限树
     */
    public void getRescTree(){
        Role role = getModel(Role.class);
        List<RoleResc> roleRescs = roleService.getRoleRescList(role);
        List<MenuResc> rescs = menuRescService.getMenuRescList();

        StringBuilder sb = new StringBuilder();
        sb.append("[");

        for (MenuResc resc : rescs) {
            sb.append("{\"id\":");
            sb.append(resc.getInt(MenuResc.ID));
            sb.append(",\"pId\":");
            sb.append(resc.getInt(MenuResc.PID));
            sb.append(",\"name\":\"");
            sb.append(resc.getStr(MenuResc.NAME));
            sb.append("\"");
            sb.append(",\"roleId\":");
            sb.append(role.getInt(Role.ID));
            sb.append(",\"open\":true");
            for(RoleResc roleResc : roleRescs){
                if(roleResc.getInt(RoleResc.RESC_ID) == resc.getInt(MenuResc.ID))
                    sb.append(",\"checked\":true");
            }
            sb.append("}");
            sb.append(",");
        }

        sb.deleteCharAt(sb.length() - 1);
        sb.append("]");
        renderText(sb.toString());
    }

    /**
     * 角色增加权限
     */
    public void addResc() {
        RoleResc roleResc = getModel(RoleResc.class);

        roleService.modifyModel(roleResc);
        renderNull();
    }

    /**
     * 角色删除权限
     */
    public void deleteResc() {
        RoleResc roleResc = getModel(RoleResc.class);

        roleService.deleteResc(roleResc);
        renderNull();
    }

}
